//
//  HomeController.m
//  BigToBig
//
//  Created by guochuangkeshi on 16/4/22.
//  Copyright © 2016年 cn.cloudtp. All rights reserved.
//

#import "HomeController.h"
#import "DidUseController.h"
#import "UnUseController.h"
#import "ExpiredController.h"
#import "SearchViewController.h"
#import "LoginModel.h"
#import "LoginViewController.h"
#import "HomeViewController.h"
#import "PullDownButton.h"

#import "ProjectViewController.h"
#import "EntrepreneurViewController.h"
#import "InvestorViewController.h"
//#import <CommonCrypto/CommonDigest.h>

@interface HomeController ()<UITextFieldDelegate,UIScrollViewDelegate>
{
        UIView *pageV;
        UIView *titleV;
        UIView *functionV;
        UIImageView *cornerV;
        PullDownButton *selectedBtn;
        PullDownButton *selectedBtn1;
        UIScrollView *scrollV;

        PullDownButton *projectBtn;
        PullDownButton *entrepreneurBtn;
        PullDownButton *investorBtn;
        UIButton *sortBtn;
        UIButton *filterBtn;
    
        BOOL isMove; //手动滑动scrollView的时候不触发点击事件的滑动效果
}
@property (nonatomic,strong) NSArray *titleArray;
@property (nonatomic,strong) UIView *headerView;
@property (nonatomic ,weak)UITextField *titleText;
@property(nonatomic,strong)UnUseController *unUseVc;
@property(nonatomic,strong)DidUseController *didUseVc;
@property(nonatomic,strong)ExpiredController *expiredVc;
@property (nonatomic , strong)ProjectViewController *projectVC;
@property (nonatomic , strong)EntrepreneurViewController *entrepreneurVC;
@property (nonatomic , strong)InvestorViewController *investorVC;

@property (nonatomic, strong)NSMutableArray *loginArray;


@end

@implementation HomeController

- (void)viewDidLoad {
    
    [super viewDidLoad];

    [self loadUserInformation];
    isMove = NO ;

    self.automaticallyAdjustsScrollViewInsets = NO;
    [self addThreeBtn];
    [self addScrollView];

    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = COLOR_RGBA(77, 155, 255, 1);
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 64)];
    titleLabel.text = @"天时";
    [titleLabel setFont:[UIFont systemFontOfSize:20]];
    titleLabel.textAlignment = 1;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.backgroundColor = [UIColor clearColor];
    [self.navigationItem setTitleView:titleLabel];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchAction:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    scrollV.showsHorizontalScrollIndicator = NO;

    scrollV.bounces = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


//程序每次启动都重新登陆一遍保证每次拿到的都是用户新的数据
- (void)loadUserInformation{
    
    NSUserDefaults* inputNub = [NSUserDefaults standardUserDefaults];
   NSString *inputNumber =  [inputNub objectForKey:@"InputNub"];
    NSUserDefaults* inputSecrte = [NSUserDefaults standardUserDefaults];
    NSString *inputSecrete = [inputSecrte objectForKey:@"Secreate"];
//    NSLog(@"%@%@",inputSecrete,inputNumber);

    
    NSDictionary *params = @{@"username":inputNumber,@"password":inputSecrete};
//    NSLog(@"*****%@",params);

    [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/user/login?" params:params success:^(id json) {
        
//        NSLog(@"%@",json);
        NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//        NSLog(@"%@",dict);
        
        NSMutableArray *loginArray = [NSMutableArray array];
        
        LoginModel *loginMD = [LoginModel LoginModelWithDict:dict];
        [loginArray addObject:loginMD];
    
        if (dict.count != 0) {

        NSUserDefaults* userID = [NSUserDefaults standardUserDefaults];
            NSString *UID = [NSString stringWithFormat:@"%@",loginMD.userid];
        [userID setObject:UID forKey:@"userID"];
        [userID synchronize];
//        NSLog(@"%@",loginMD.userid);
        
        NSUserDefaults* sdkLoginName = [NSUserDefaults standardUserDefaults];
        [sdkLoginName setObject:loginMD.primary_key forKey:@"loginName"];
//        NSLog(@"%@",loginMD.primary_key);
        [sdkLoginName synchronize];
            
        NSUserDefaults* name = [NSUserDefaults standardUserDefaults];
        [name setObject:loginMD.name forKey:@"name"];
        [name synchronize];
//        NSLog(@"%@",loginMD.name);

        
        NSUserDefaults* userType = [NSUserDefaults standardUserDefaults];
        [userType setObject:loginMD.user_type forKey:@"userTyp"];
        [userType synchronize];
            
        NSUserDefaults* phoneNumberDefaults = [NSUserDefaults standardUserDefaults];
        [phoneNumberDefaults setObject:loginMD.telephone forKey:@"phoneNumber"];
        [phoneNumberDefaults synchronize];
            
        NSUserDefaults* emailDefaults = [NSUserDefaults standardUserDefaults];
        [emailDefaults setObject:loginMD.email forKey:@"email"];
        [emailDefaults synchronize];
        
        NSUserDefaults* jobDefaults = [NSUserDefaults standardUserDefaults];
        [jobDefaults setObject:loginMD.job_title forKey:@"jobName"];
        [jobDefaults synchronize];
            
        NSUserDefaults* weChatDefaults = [NSUserDefaults standardUserDefaults];
        [weChatDefaults setObject:loginMD.wechat forKey:@"weChat"];
        [weChatDefaults synchronize];
        
        NSUserDefaults* companyDefaults = [NSUserDefaults standardUserDefaults];
        [companyDefaults setObject:loginMD.company_name forKey:@"company"];
        [companyDefaults synchronize];
        
        NSUserDefaults* adressDefaults = [NSUserDefaults standardUserDefaults];
        [adressDefaults setObject:loginMD.city forKey:@"adress"];
        [adressDefaults synchronize];
            
//        NSLog(@"%@",loginMD.user_type);
          
            [self sdkLogin];

        }else{
        

            [UIView animateWithDuration:1.0 animations:^{
                
                MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
                HUD.labelText = @"密码被修改请重新登录";
                HUD.mode = MBProgressHUDModeIndeterminate;
                [HUD hide:YES afterDelay:1.0];
                
            } completion:^(BOOL finished) {
                
                UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:[HomeViewController new]];
                
                KeyWindow.rootViewController = nav;
                
            }];

            

        }
        
        
    } failure:^(NSError *error) {
        
        

        
    }];
}


- (void)sdkLogin{

    
    NSUserDefaults* inputSecrteDefaults = [NSUserDefaults standardUserDefaults];
    NSString *inputSecrete = [inputSecrteDefaults objectForKey:@"Secreate"];
    
    NSUserDefaults *sdkLoginName1 = [NSUserDefaults standardUserDefaults];
    NSString *loginName = [sdkLoginName1 objectForKey:@"loginName"];
    NSLog(@"%@",loginName);
    
    [AVCamViewController getLoginUserInfo:loginName withPassword:inputSecrete withBlock:^(NSString *code, NSInteger activityId, NSInteger userId, NSString *tokenId) {
        
        //登陆成功
        if ([code isEqualToString:@"0"])
        {
            
            
            NSLog(@"%ld",activityId);
            
            NSString *str = [NSString stringWithFormat:@"%ld",activityId];
            NSUserDefaults *activityIdDefaults = [NSUserDefaults standardUserDefaults];
            [activityIdDefaults setObject:str forKey:@"activty_id"];
            [activityIdDefaults synchronize];
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
            });
            
        }else
        {
//            NSLog(@"登陆失败");
        }
    }];

}
- (ProjectViewController *)projectVC{
    if (_projectVC == nil) {
        _projectVC = [[ProjectViewController alloc]init];
        
    }
    [self addChildViewController:_projectVC];
    return _projectVC;
}

- (EntrepreneurViewController *)entrepreneurVC{
    if (_entrepreneurVC == nil) {
        _entrepreneurVC = [[EntrepreneurViewController alloc]init];
    }
    [self addChildViewController:_entrepreneurVC];
    return _entrepreneurVC;
}

- (InvestorViewController *)investorVC{
    if (_investorVC == nil) {
        _investorVC = [[InvestorViewController alloc]init];
    }
    [self addChildViewController:_investorVC];
    return _investorVC;
}


- (void)addThreeBtn{
    
    titleV = [[UIView alloc]initWithFrame:CGRectMake(20, 84, kScreenWidth - 40, 36)];
    [self.view addSubview:titleV];
    projectBtn = [PullDownButton createButtonWithTitle:@"创业项目" frame:CGRectMake(0,0,(kScreenWidth - 40)/3 ,20) tag:1000];
    [titleV addSubview:projectBtn];
    [projectBtn addTarget:self action:@selector(buttonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    entrepreneurBtn = [PullDownButton createButtonWithTitle:@"创业者" frame:CGRectMake(projectBtn.maxX , 0,(kScreenWidth - 40)/3,20) tag:1001];
    [titleV addSubview:entrepreneurBtn];
    [entrepreneurBtn addTarget:self action:@selector(buttonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    investorBtn = [PullDownButton createButtonWithTitle:@"投资人" frame:CGRectMake(entrepreneurBtn.maxX ,0,(kScreenWidth - 40) / 3 , 20) tag:1002];
    [titleV addSubview:investorBtn];
    [investorBtn addTarget:self action:@selector(buttonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    if (selectedBtn1==nil) {
        
        projectBtn.selected = YES;
        projectBtn.downImageView.image = [UIImage imageNamed:@"xl-selected"];
        [projectBtn.titleLabel setFont:[UIFont systemFontOfSize:projectBtn.frame.size.width / 6 * 5 / 6 + 1]];
        
        selectedBtn1 = projectBtn;
    }
    
}



- (void)buttonClickAction:(PullDownButton *)button{
    if (selectedBtn1 == button) {
        return;
    }
    else{
        button.selected = YES;
        selectedBtn1.selected = NO;
        [button.titleLabel setFont:[UIFont systemFontOfSize:17]];
        button.downImageView.image = [UIImage imageNamed:@"xl-selected"];
        [selectedBtn1.titleLabel setFont:[UIFont systemFontOfSize:projectBtn.frame.size.width / 6 * 5 / 6 ]];
        selectedBtn1.downImageView.image = [UIImage imageNamed:@"xl-button"];
        selectedBtn1 = button;
        [UIView animateWithDuration:.3 animations:^{
            if (!isMove) {
    
                [scrollV setContentOffset:CGPointMake((button.tag - 1000) * kScreenWidth, 0)];
            }
    
        } completion:^(BOOL finished) {
            
            isMove = NO;
        }];
        
    }
    
}


- (void)addScrollView{
    

    scrollV=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 115, kScreenWidth, kScreenHeight-115-49)];
    scrollV.backgroundColor = [UIColor redColor];
    scrollV.contentSize = CGSizeMake(3*kScreenWidth, scrollV.height);
    scrollV.pagingEnabled = YES;
    scrollV.delegate = self;
    [self.view addSubview:scrollV];
    self.projectVC.view.frame = CGRectMake(0, 0, kScreenWidth, scrollV.height);
    [scrollV addSubview:_projectVC.view];
    self.entrepreneurVC.view.frame = CGRectMake(kScreenWidth , 0 , kScreenWidth, scrollV.height);
    [scrollV addSubview:_entrepreneurVC.view];
    self.investorVC.view.frame = CGRectMake(kScreenWidth * 2, 0, kScreenWidth, scrollV.height);
    [scrollV addSubview:_investorVC.view];
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    isMove = YES;
    
    CGFloat offsetX = scrollView.contentOffset.x;
    
    if (offsetX >= 0 &&offsetX<kScreenWidth / 2) {
        [self buttonClickAction:projectBtn];
    }
    else if(offsetX >= kScreenWidth / 2 && offsetX < kScreenWidth / 2 * 3){
        [self buttonClickAction:entrepreneurBtn];
    }
    else if(offsetX >= kScreenWidth / 2 * 3){
        [self buttonClickAction:investorBtn];
    }
    
}

- (void)searchAction:(UIBarButtonItem *)buttonItem{

    SearchViewController *searchVc = [[SearchViewController alloc]init];
    [self.navigationController pushViewController:searchVc animated:YES];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    isMove = NO;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self.titleText endEditing:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
   return [self.titleText endEditing:YES];
}


@end
